﻿/*+===================================================================
File:      EnemyMachine.cpp

Summary:   Định nghĩa các phương thức của CEnemyMachine.
===================================================================+*/

#include "EnemyMachine.h"
#include "Explosion.h"
#include "PlayState.h"

#define STATUS_STAND 0
#define STATUS_FIRE  1

CEnemyMachine::CEnemyMachine(D3DXVECTOR2 pos, int id, int typeId) : CMoveableObject(pos, id, typeId)
{
	CResourcesManager::GetInstance()->GetSprite(ID_SPRITE_ENEMY_MACHINE_STAND);
	CResourcesManager::GetInstance()->GetSprite(ID_SPRITE_ENEMY_MACHINE_FIRE);
	m_nStatus = STATUS_STAND;
	m_pSprite = m_pResourceManager->GetSprite(ID_SPRITE_ENEMY_MACHINE_STAND);
	m_pGun = new CGun(ID_ENEMY_BIG_BULLET, 1, 1);
	m_pGun->SetBulletAngle(180.0f);
	m_nLife = 20;
}


CEnemyMachine::~CEnemyMachine()
{
	if (m_pGun)
		delete m_pGun;
}

void CEnemyMachine::UpdateAnimation()
{
	switch (m_nStatus)
	{
		case STATUS_STAND:
			m_pSprite = m_pResourceManager->GetSprite(ID_SPRITE_ENEMY_MACHINE_STAND);
			break;
		case STATUS_FIRE:
			m_pSprite = m_pResourceManager->GetSprite(ID_SPRITE_ENEMY_MACHINE_FIRE);
			break;
	}
}

void CEnemyMachine::Update(float timeFrame)
{
	if (!m_bIsLive)
		return;

	if (m_nStatus == STATUS_FIRE)
	{
		if (m_fTimeFire > 0)
		{
			m_fTimeFire -= timeFrame;
		}
		else
		{
			m_fTimeFire = 0.0f;
			m_nStatus = STATUS_STAND;
		}
	}

	if (m_nStatus == STATUS_STAND)
	{
		if (m_pGun->IsFullBullets())
		{
			D3DXVECTOR2 bulletPos;
			bulletPos.x = m_pos.x - m_pSprite->GetWidth() / 2.0f;
			bulletPos.y = m_pos.y + m_pSprite->GetHeight() / 2.0f - 15.0f;
			m_pGun->Fire(bulletPos);

			m_nStatus = STATUS_FIRE;
			m_fTimeFire = 0.3f;
		}
	}

	UpdateAnimation();
	m_pSprite->Update(timeFrame);
	UpdateBox(timeFrame);
}

void CEnemyMachine::UpdateCollision(vector<CGameObject*> vecGameObjs, float timeFrame)
{
	if (!m_bIsLive)
		return;

	float timeCollision = timeFrame;
	CGameObject* objCollision = NULL; // Đối tượng va chạm sớm nhất.
	float normalx = 0.0f, normaly = 0.0f;

	// Xử lí va chạm với đạn của Bill
	for (int i = 0; i < CPlayState::s_billBullets.size(); i++)
	{
		if (CPlayState::s_billBullets[i]->IsLive())
		{
			float t = CheckCollision(CPlayState::s_billBullets[i], normalx, normaly, timeFrame);

			if (t < timeFrame && t < timeCollision)
			{
				// Tìm đối tượng và thời gian va chạm sớm nhất.
				timeCollision = t;
				objCollision = CPlayState::s_billBullets[i];
			}
		}
	}

	// Xử lí va chạm
	if (objCollision != NULL)
	{
		this->Kill();
		objCollision->Kill();
	}
}

bool CEnemyMachine::Kill()
{
	if (m_nLife > 1)
		m_nLife--;
	else
	{
		m_bIsLive = false;
		CExplosion* ex = new CExplosion(m_pos, 0, ID_SMALL_EXPLOSION);
		CPlayState::s_objsOutSideQuadTree.push_back(ex);
	}
	g_nScore += 500;
	return true;
}